﻿using System.IO;
using System.Windows;
using System.Windows.Forms;
using LisenceUtils.Enums;
using Application = System.Windows.Forms.Application;
using MessageBox = System.Windows.Forms.MessageBox;

namespace LisenceUtils.Windows
{
    public partial class LincenseActivate : Window
    {
        public LincenseActivate()
        {
            InitializeComponent();
        }

        public string AppName { get; set; }

        public byte[] CertificatePublicKeyData { get; set; }


        public string LicenseBase64String => TxtLicense.Text.Trim();


        public bool ValidateLicense()
        {
            if (string.IsNullOrWhiteSpace(TxtLicense.Text))
            {
                MessageBox.Show("请输入密钥", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            var lic = MyLicense.Default.ParseLicenseFromBase64String(TxtLicense.Text.Trim(), CertificatePublicKeyData);
            if (lic == null)
            {
                MessageBox.Show("密钥无效", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            switch (lic?.LicenseStatus)
            {
                case LicenseStatus.Valid:
                    MessageBox.Show("验证成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return true;

                case LicenseStatus.Cracked:
                case LicenseStatus.Invalid:
                case LicenseStatus.Undefined:
                    MessageBox.Show("密钥无效", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                default:
                    return false;
            }
        }

        private void Ok(object sender, RoutedEventArgs e)
        {
            if (ValidateLicense())
            {
                File.WriteAllText(Path.Combine(Application.StartupPath, ConstInfo.LicenseFile), LicenseBase64String);
                DialogResult = true;
                Visibility = Visibility.Collapsed;
            }
        }

        private void Cancel(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Visibility = Visibility.Collapsed;
        }
    }
}